#include <stdio.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "freertos/queue.h"
#include "button.h"
#include "led.h"
#include "key.h"
#include "nvs_app.h"



static struct button_obj_t button1;
static void single_click_handle(void* btn);
static void double_click_handle(void* btn);
static void long_press_handle(void* btn);


extern uint16_t rs485_baud;
extern char spp_name[16];
extern led_obj_t* led1_obj;

static const key_value_match_map_t button1_map[] =
{
    {
        .tar_result = SINGLE_CLICK_KV,
        .kv_func_cb = single_click_handle
    },
    {
        .tar_result = DOUBLE_CLICK_KV,
        .kv_func_cb = double_click_handle
    },
    {
        .tar_result = LONG_PRESEE_START,
        .kv_func_cb = long_press_handle
    }
};

static uint8_t read_button_pin(uint8_t button_id)
{
    switch(button_id)
    {
        case 0:
            return BSP_GPIO_KEY_LEVEL(BSP_GPIO_KEY1);
            break;

        default:
            return 0;
            break;
    }
    return 0;
}

static void single_click_handle(void* btn)
{
    printf("/****single click****/\r\n");
}

static void double_click_handle(void* btn)
{
    printf("/****double click****/\r\n");
}

static void long_press_handle(void* btn)
{
    printf("/****long press****/\r\n");
    rs485_baud = 96;
    char spp_name_temp[16] = {'B','T','_','P','O','R','T','_','N','A','M','E','\0','\0','\0','\0'};
    memcpy(spp_name, spp_name_temp, 16);
    nvs_write_send(NVS_BAUD);
    nvs_write_send(NVS_SPP_NAME);
    led_ctrl(led1_obj, LED_ON);
}

static void key_task(void* arg)
{
    if(!arg)
    {
        return;
    }
    while(1)
    {
        button_ticks();
        vTaskDelay(20 / portTICK_PERIOD_MS);
    }
}

void key_app_main(void)
{
    BSP_GPIO_KEY_INIT(BSP_GPIO_KEY1);
    button_init(&button1, read_button_pin, 0, 0, button1_map, ARRAY_SIZE(button1_map));
    button_start(&button1);
    xTaskCreate(key_task, "key_task", 2048, &button1, 5, NULL);
}







